<?php
class User
{
	
	private $login;
	private $pwd;
	
	private $uid;
	private $ssid = false;
	
	private $legit = false;
	
	private $prefs; // user preferences
	
	function __construct($login)
	{
		if(empty($login))
			return false;
		
		$this->login = $login;
		$_SESSION['user'] = $login;
				
		// Loads user from db
		$d = new Database();
		$ar = array();
		$ar['login'] = $d->secure($login);
		$d->select('users','*',$ar);
		
		if($d->num_rows() < 1) // user doesn't exist
			return false;
		elseif($d->num_rows() > 1) // more than 1 user with this username, we have a security issue here
			return false;
		
		$data = $d->fetch_all(); // data[user[login = .., pwd = ...]]
		$user = $data[0];
				
		$this->pwd = $user['pwd'];
		$this->uid = $_SESSION['uid'] = $user['id'];
		
		
		// get the ssid
		$ar = array();
		$ar['uid'] = $this->uid;
		$d->select('sessions','ssid',$ar);
		
		if($d->num_rows() < 1) // session doesn't exist
			return false;
		elseif($d->num_rows() > 1) // more than 1 session for this user, we have a security issue here
			return false;
			
		$data = $d->fetch_all(); // data[session[ssid = ...]]
		$ss = $data[0];
		$this->ssid = $ss['ssid'];
		
		// get user preferences
		$this->prefs = Preferences::loadForUser($this->uid);
			
	}
	
	public function chkPwd($pwd)
	{
		if($this->getPwd() == sha1($pwd))
			return true;
		else
			return false;
	}
	
	########################
	# Getters
	
	public function getLogin()
	{
		return $this->login;
	}
	
	public function getPwd()
	{
		return $this->pwd;
	}
	
	public function getId()
	{
		return $this->uid;
	}
	
	public function getSession()
	{
		return $this->ssid;
	}
	
	public function getPreferences()
	{
		return $this->prefs;
	}
	
	public function isLegit()
	{
		return $this->legit;
	}
	
	########################
	# Setters
	
	public function setAuth($legit)
	{
		if($legit)
			$this->legit = true;
		else
			$this->legit = false;
			
		return $this->legit;
	}
		
	public function setSession($ssid)
	{
		$this->ssid = $ssid;
	}
	
}
?>